package com.xc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.code.kaptcha.Constants;
import com.xc.common.Const;
import com.xc.common.ServerResponse;
import com.xc.dao.SiteAdminMapper;
import com.xc.pojo.SiteAdmin;
import com.xc.pojo.UserRecharge;
import com.xc.service.*;
import com.xc.utils.PropertiesUtil;
import com.xc.utils.redis.RedisShardedPoolUtils;
import com.xc.vo.admin.AdminCountVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author mipha
 * @version 1.0
 * @date 2019/2/16 2:53 PM
 */
@Service("iSiteAdminServiceImpl")
@Slf4j
public class SiteAdminServiceImpl implements ISiteAdminService {

    @Autowired
    SiteAdminMapper siteAdminMapper;
    @Autowired
    IUserRechargeService iUserRechargeService;
    @Autowired
    IUserService iUserService;
    @Autowired
    IUserWithdrawService iUserWithdrawService;
    @Autowired
    IUserPositionService iUserPositionService;
    @Autowired
    IAgentUserService iAgentUserService;
    @Autowired
    IStockService iStockService;


    @Override
    public ServerResponse login(String adminPhone, String adminPwd, String verifyCode, HttpServletRequest request) {

        if(StringUtils.isBlank(verifyCode)){
            return ServerResponse.createByErrorMsg("验证码不能为空");
        }
        String original = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (!verifyCode.equalsIgnoreCase(original)) {
            return ServerResponse.createByErrorMsg("验证码错误");
        }

        if(StringUtils.isBlank(adminPhone) || StringUtils.isBlank(adminPwd)){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        SiteAdmin siteAdmin = siteAdminMapper.login(adminPhone,adminPwd);
        if(siteAdmin == null){
            return ServerResponse.createByErrorMsg("账号密码错误");
        }

        if(siteAdmin.getIsLock() == Const.SiteAdminLockStatus.lock){
            return ServerResponse.createByErrorMsg("账号已被锁定");
        }

        siteAdmin.setAdminPwd(null);
        return ServerResponse.createBySuccess(siteAdmin);
    }

    @Override
    public ServerResponse<PageInfo> listByAdmin(String adminName, String adminPhone, HttpServletRequest request, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);

        String superAdmin = PropertiesUtil.getProperty("admin.super.name");

        List<SiteAdmin> siteAdmins = siteAdminMapper.listByAdmin(adminName,adminPhone,superAdmin);

        PageInfo pageInfo = new PageInfo(siteAdmins);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse authCharge(String token, Integer state, String orderSn) {

        if(StringUtils.isBlank(token) || state == null || StringUtils.isBlank(orderSn)) {
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        //  判断token是否失效
        String redis_token = RedisShardedPoolUtils.get(token);
        if(StringUtils.isBlank(redis_token)){
            return ServerResponse.createByErrorMsg("token错误或已过有效期");
        }

        //  查询订单
        ServerResponse serverResponse = iUserRechargeService.findUserRechargeByOrderSn(orderSn);
        if(!serverResponse.isSuccess()){
            return serverResponse;
        }

        UserRecharge userRecharge = (UserRecharge)serverResponse.getData();
        ServerResponse returnResponse = null;
        try {
            if(state == Const.UserRechargeStatus.charge_success){
                returnResponse = iUserRechargeService.chargeSuccess(userRecharge);
            }else if(state == Const.UserRechargeStatus.charge_fail){
                returnResponse = iUserRechargeService.chargeFail(userRecharge);
            }else if(state == Const.UserRechargeStatus.charge_cancel){
                returnResponse = iUserRechargeService.chargeCancel(userRecharge);
            }else{
                return ServerResponse.createByErrorMsg("状态不对，不做处理");
            }
        }catch (Exception e){
            log.error("email 审核入金状态出错，错误信息 = {}" , e);
        }

        return returnResponse;
    }

    @Override
    public ServerResponse updateLock(Integer adminId) {
        SiteAdmin siteAdmin = siteAdminMapper.selectByPrimaryKey(adminId);
        if(siteAdmin == null){
            return ServerResponse.createByErrorMsg("管理员不存在");
        }

        if(siteAdmin.getIsLock() == Const.SiteAdminLockStatus.zhengchang){
            siteAdmin.setIsLock(Const.SiteAdminLockStatus.lock);
        }else{
            siteAdmin.setIsLock(Const.SiteAdminLockStatus.zhengchang);
        }

        int updateCount = siteAdminMapper.updateByPrimaryKeySelective(siteAdmin);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMsg("修改成功");
        }else{
            return ServerResponse.createByErrorMsg("修改失败");
        }

    }

    @Override
    public ServerResponse add(SiteAdmin siteAdmin) {
        if(StringUtils.isBlank(siteAdmin.getAdminName())
                || StringUtils.isBlank(siteAdmin.getAdminPhone())
                || StringUtils.isBlank(siteAdmin.getAdminPwd())
                || siteAdmin.getIsLock() == null
                ){
            return ServerResponse.createByErrorMsg("参数不能为空");
        }

        SiteAdmin siteAdmin1 = siteAdminMapper.findAdminByName(siteAdmin.getAdminName());
        if(siteAdmin1 != null){
            return ServerResponse.createByErrorMsg("管理名存在");
        }
        SiteAdmin siteAdmin2 = siteAdminMapper.findAdminByPhone(siteAdmin.getAdminPhone());
        if(siteAdmin2 != null){
            return ServerResponse.createByErrorMsg("手机号存在");
        }

        SiteAdmin dbadmin = new SiteAdmin();
        dbadmin.setAdminName(siteAdmin.getAdminName());
        dbadmin.setAdminPhone(siteAdmin.getAdminPhone());
        dbadmin.setAdminPwd(siteAdmin.getAdminPwd());
        dbadmin.setIsLock(siteAdmin.getIsLock());
        dbadmin.setAddTime(new Date());

        int insertCount = siteAdminMapper.insert(dbadmin);
        if(insertCount > 0){
            return ServerResponse.createBySuccessMsg("添加成功");
        }else{
            return ServerResponse.createByErrorMsg("添加失败");
        }
    }

    @Override
    public ServerResponse update(SiteAdmin siteAdmin) {
        if(siteAdmin.getId() == null){
            return ServerResponse.createByErrorMsg("修改id不能为空");
        }

        int updateCount = siteAdminMapper.updateByPrimaryKeySelective(siteAdmin);
        if(updateCount > 0){
            return ServerResponse.createBySuccessMsg("修改成功");
        }else{
            return ServerResponse.createByErrorMsg("修改失败");
        }
    }


    @Override
    public SiteAdmin findAdminByName(String name) {
        return siteAdminMapper.findAdminByName(name);
    }

    @Override
    public SiteAdmin findAdminByPhone(String phone) {
        return siteAdminMapper.findAdminByPhone(phone);
    }

    @Override
    public ServerResponse count() {

        AdminCountVO adminCountVO = new AdminCountVO();

        int user_sp_num = iUserService.CountUserSize(Const.UserAccountType.zhengshi);
        int user_moni_num = iUserService.CountUserSize(Const.UserAccountType.moni);
        adminCountVO.setUser_sp_num(user_sp_num);
        adminCountVO.setUser_moni_num(user_moni_num);

        int agent_num = iAgentUserService.CountAgentNum();
        adminCountVO.setAgent_num(agent_num);

        //  统计用户资金 总资金和可用资金
        BigDecimal user_sp_sum_amt = iUserService.CountUserAmt(Const.UserAccountType.zhengshi);
        BigDecimal user_sp_sum_enable = iUserService.CountEnableAmt(Const.UserAccountType.zhengshi);
        adminCountVO.setUser_sp_sum_amt(user_sp_sum_amt);
        adminCountVO.setUser_sp_sum_enable(user_sp_sum_enable);

        BigDecimal charge_sum_amt = iUserRechargeService.CountChargeSumAmt(Const.UserRechargeStatus.charge_success);
        BigDecimal sp_withdraw_sum_amt_success = iUserWithdrawService
                .CountSpWithSumAmtByState(Const.UserWithdrawStatus.trans_success);
        BigDecimal sp_withdraw_sum_amt_apply = iUserWithdrawService
                .CountSpWithSumAmtByState(Const.UserWithdrawStatus.apply_status);
        adminCountVO.setCharge_sum_amt(charge_sum_amt);
        adminCountVO.setSp_withdraw_sum_amt_success(sp_withdraw_sum_amt_success);
        adminCountVO.setSp_withdraw_sum_amt_apply(sp_withdraw_sum_amt_apply);

        //  持仓单 1  平仓单 2
        int sp_position_num = iUserPositionService.CountPositionNum(1, Const.UserAccountType.zhengshi);
        int sp_pc_position_num = iUserPositionService.CountPositionNum(2, Const.UserAccountType.zhengshi);
        adminCountVO.setSp_position_num(sp_position_num);
        adminCountVO.setSp_pc_position_num(sp_pc_position_num);

        //  查询所有平仓单的 浮动盈亏和总盈亏
        BigDecimal sp_profit_and_lose = iUserPositionService.CountPositionProfitAndLose();
        BigDecimal sp_all_profit_and_lose = iUserPositionService.CountPositionAllProfitAndLose();
        adminCountVO.setSp_profit_and_lose(sp_profit_and_lose);
        adminCountVO.setSp_all_profit_and_lose(sp_all_profit_and_lose);

        int stock_num = iStockService.CountStockNum();
        int stock_show_num = iStockService.CountShowNum(Const.StockShow.show);
        int stock_un_lock_num = iStockService.CountUnLockNum(Const.StockLock.no_lock);
        adminCountVO.setStock_num(stock_num);
        adminCountVO.setStock_show_num(stock_show_num);
        adminCountVO.setStock_un_lock_num(stock_un_lock_num);

        return ServerResponse.createBySuccess(adminCountVO);
    }


    public static void main(String[] args) {
        System.out.println(RedisShardedPoolUtils.get("1"));
        System.out.println(RedisShardedPoolUtils.get("2"));
    }



}

